//
//  UIGestureRecognizer+ClickBlock.m
//  tools
//
//  Created by hyjet on 2018/3/14.
//  Copyright © 2018年 tools. All rights reserved.
//

#import "UIGestureRecognizer+ActionBlock.h"
#import <objc/runtime.h>

static const int target_gesture_key;
@implementation UIGestureRecognizer (ActionBlock)

+(instancetype)cw_gestureWithActionBlock:(CWActionBlock)block {
    return [[self alloc]initWithActionBlock:block];
}

- (instancetype)initWithActionBlock:(CWActionBlock)block {
    self = [self init];
    [self cw_addActionBlock:block];
    return self;
}

- (void)cw_addActionBlock:(CWActionBlock)block {
    self.block = [block copy];
    [self addTarget:self action:@selector(event:)];
}

- (void)event:(id)sender {
    if (self.block) {
        self.block(sender);
    }
}

-(void)setBlock:(CWActionBlock)block
{
    objc_setAssociatedObject(self, &target_gesture_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(CWActionBlock)block
{
    return objc_getAssociatedObject(self, &target_gesture_key);
}

@end


static const int target_button_key;
@implementation UIButton (ActionBlock)

+(instancetype)cw_buttonWithActionEvents:(UIControlEvents)controlEvents Block:(CWActionBlock)block {
    return [[self alloc]initWithActionEvents:controlEvents block:block];
}

- (instancetype)initWithActionEvents:(UIControlEvents)controlEvents block:(CWActionBlock)block {
    self = [self init];
    [self cw_addActionEvents:controlEvents block:block];
    return self;
}

- (void)cw_addActionEvents:(UIControlEvents)controlEvents block:(CWActionBlock)block {
    self.block = [block copy];
    [self addTarget:self action:@selector(event:) forControlEvents:controlEvents];
}

- (void)event:(id)sender {
    if (self.block) {
        self.block(sender);
    }
}

-(void)setBlock:(CWActionBlock)block
{
    objc_setAssociatedObject(self, &target_button_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(CWActionBlock)block
{
    return objc_getAssociatedObject(self, &target_button_key);
}


@end
